package uk.co.revisual.domino.controller.cmds
{
	import org.puremvc.as3.multicore.interfaces.ICommand;
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.command.SimpleCommand;
	import org.puremvc.as3.multicore.utilities.statemachine.State;
	
	import uk.co.revisual.domino.core.FSMFacade;
	import uk.co.revisual.domino.consts.DominoConsts;

	public class ExecuteCommandClassCmd extends SimpleCommand
	{
		private var _stateEventName:String;
		private var _fsmAccessor:FSMFacade;
		
		// this command can be wrapped by a notifier to define the stateEventName
		public function ExecuteCommandClassCmd( stateEventName:String = null ):void{
			_stateEventName = stateEventName;
		}
		
		override public function execute(note:INotification):void{
			// get our actors
			_fsmAccessor = new FSMFacade();
			_fsmAccessor.initializeNotifier( multitonKey );
			
			// retrieve the commandClass and get the class from the factory;
			_stateEventName = ( _stateEventName != null ) ? _stateEventName : note.getName();
			var statename:String = getStateName();
			var commandPath:String = _fsmAccessor.model.getCommandPath( statename, _stateEventName );
			if(commandPath == null) return;
			var commandClass:Class = _fsmAccessor.factory.create( commandPath ) as Class;
			if(commandClass == null) return;
			// execute command
			var command:ICommand = new commandClass();
			command.initializeNotifier( multitonKey);
			command.execute( note );
		}
		
		
		private function getStateName():String{
			var currentReferringAction:String = _fsmAccessor.history.currentReferringAction;
			var currentState:State;
			if( currentReferringAction == "initial" ){
				currentState = State( _fsmAccessor.stateMachine.getViewComponent() );
				return currentState.name;
			}else if( _stateEventName == DominoConsts.EVENT_NODES_NAMES.ENTERING_GUARD){
				currentState = _fsmAccessor.history.currentState;
				return currentState.getTarget( currentReferringAction )
			}else{
				currentState = _fsmAccessor.history.currentState;
				return currentState.name
			}
		}
		
	}
}